<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.Title}}</title>
    <link href="/static/libs/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/libs/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <link href="/static/css/app.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-database"></i>
                PGM - PostgreSQL管理平台
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">
                            <i class="bi bi-house"></i>
                            首页
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/api/tables">
                            <i class="bi bi-table"></i>
                            API文档
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8 mx-auto">
        <!-- 头部 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3">
                    <i class="bi bi-pencil-square"></i>
                    编辑记录
                </h1>
                <p class="text-muted mb-0">编辑表 <strong>{{.TableName}}</strong> 中的记录 (ID: {{.ID}})</p>
            </div>
            <a href="/table/{{.TableName}}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i>
                返回
            </a>
        </div>

        <!-- 加载状态 -->
        <div id="loadingState" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2 text-muted">正在加载记录信息...</p>
        </div>

        <!-- 表单 -->
        <div class="card" id="editCard" style="display: none;">
            <div class="card-header">
                <h5 class="mb-0">记录信息</h5>
            </div>
            <div class="card-body">
                <form id="editForm">
                    {{range .Table.Columns}}
                    <div class="mb-3">
                        <label for="{{.Name}}" class="form-label">
                            {{.Name}}
                            {{if .Comment}}
                                <small class="text-muted">({{.Comment}})</small>
                            {{end}}
                            {{if not .IsNullable}}
                                <span class="text-danger">*</span>
                            {{end}}
                            {{if contains $.Table.PrimaryKeys .Name}}
                                <span class="badge bg-primary">主键</span>
                            {{end}}
                        </label>
                        
                        {{if eq .DataType "boolean"}}
                            <select class="form-select" id="{{.Name}}" name="{{.Name}}" 
                                {{if contains $.Table.PrimaryKeys .Name}}disabled{{end}}
                                {{if not .IsNullable}}required{{end}}>
                                {{if .IsNullable}}<option value="">请选择</option>{{end}}
                                <option value="true">True</option>
                                <option value="false">False</option>
                            </select>
                        {{else if eq .DataType "text"}}
                            <textarea class="form-control" id="{{.Name}}" name="{{.Name}}" rows="3" 
                                placeholder="请输入{{.Name}}" 
                                {{if contains $.Table.PrimaryKeys .Name}}readonly{{end}}
                                {{if not .IsNullable}}required{{end}}></textarea>
                        {{else if contains .DataType "int"}}
                            <input type="number" class="form-control" id="{{.Name}}" name="{{.Name}}" 
                                placeholder="请输入{{.Name}}" 
                                {{if contains $.Table.PrimaryKeys .Name}}readonly{{end}}
                                {{if not .IsNullable}}required{{end}}>
                        {{else if or (contains .DataType "decimal") (contains .DataType "numeric") (contains .DataType "real") (contains .DataType "double")}}
                            <input type="number" step="any" class="form-control" id="{{.Name}}" name="{{.Name}}" 
                                placeholder="请输入{{.Name}}" 
                                {{if contains $.Table.PrimaryKeys .Name}}readonly{{end}}
                                {{if not .IsNullable}}required{{end}}>
                        {{else if contains .DataType "date"}}
                            <input type="datetime-local" class="form-control" id="{{.Name}}" name="{{.Name}}" 
                                {{if contains $.Table.PrimaryKeys .Name}}readonly{{end}}
                                {{if not .IsNullable}}required{{end}}>
                        {{else}}
                            <input type="text" class="form-control" id="{{.Name}}" name="{{.Name}}" 
                                placeholder="请输入{{.Name}}" 
                                {{if .MaxLength}}maxlength="{{.MaxLength}}"{{end}}
                                {{if contains $.Table.PrimaryKeys .Name}}readonly{{end}}
                                {{if not .IsNullable}}required{{end}}>
                        {{end}}
                        
                        <div class="form-text">
                            类型: {{.DataType}}
                            {{if .MaxLength}} | 最大长度: {{.MaxLength}}{{end}}
                            {{if not .IsNullable}} | 必填字段{{end}}
                            {{if contains $.Table.PrimaryKeys .Name}} | 主键字段（不可修改）{{end}}
                        </div>
                    </div>
                    {{end}}

                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                        <button type="button" class="btn btn-outline-secondary" onclick="loadRecord()">
                            <i class="bi bi-arrow-clockwise"></i>
                            重载数据
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check"></i>
                            保存修改
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 错误状态 -->
        <div id="errorState" class="alert alert-danger" style="display: none;">
            <i class="bi bi-exclamation-triangle"></i>
            <span id="errorMessage"></span>
        </div>
    </div>
</div>

<script>
const tableInfo = {
    name: '{{.TableName}}',
    recordId: '{{.ID}}',
    columns: [
        {{range .Table.Columns}}
        {
            name: '{{.Name}}',
            dataType: '{{.DataType}}',
            isNullable: {{.IsNullable}},
            isPrimaryKey: {{contains $.Table.PrimaryKeys .Name}}
        },
        {{end}}
    ]
};

// 页面加载时获取记录数据
document.addEventListener('DOMContentLoaded', function() {
    loadRecord();
});

// 加载记录数据
function loadRecord() {
    document.getElementById('loadingState').style.display = 'block';
    document.getElementById('editCard').style.display = 'none';
    document.getElementById('errorState').style.display = 'none';

    fetch(`/api/data/${tableInfo.name}/${tableInfo.recordId}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                fillForm(data.data);
                document.getElementById('loadingState').style.display = 'none';
                document.getElementById('editCard').style.display = 'block';
            } else {
                showError('加载记录失败: ' + data.message);
            }
        })
        .catch(error => {
            showError('网络错误: ' + error.message);
        });
}

// 填充表单数据
function fillForm(record) {
    tableInfo.columns.forEach(column => {
        const field = document.getElementById(column.name);
        if (field && record.hasOwnProperty(column.name)) {
            const value = record[column.name];
            
            if (value === null || value === undefined) {
                field.value = '';
            } else if (column.dataType === 'boolean') {
                field.value = value.toString();
            } else if (column.dataType.includes('date') || column.dataType.includes('timestamp')) {
                // 处理日期时间格式
                if (typeof value === 'string') {
                    const date = new Date(value);
                    if (!isNaN(date.getTime())) {
                        // 转换为本地时间格式 (YYYY-MM-DDTHH:mm)
                        const year = date.getFullYear();
                        const month = String(date.getMonth() + 1).padStart(2, '0');
                        const day = String(date.getDate()).padStart(2, '0');
                        const hours = String(date.getHours()).padStart(2, '0');
                        const minutes = String(date.getMinutes()).padStart(2, '0');
                        field.value = `${year}-${month}-${day}T${hours}:${minutes}`;
                    } else {
                        field.value = value;
                    }
                } else {
                    field.value = value;
                }
            } else {
                field.value = value;
            }
        }
    });
}

// 表单提交处理
document.getElementById('editForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const data = {};
    
    // 收集表单数据
    for (let [key, value] of formData.entries()) {
        const column = tableInfo.columns.find(col => col.name === key);
        if (column && !column.isPrimaryKey) { // 不更新主键字段
            if (value === '') {
                data[key] = null;
            } else {
                // 根据字段类型转换数据
                if (column.dataType === 'boolean') {
                    data[key] = value === 'true';
                } else if (column.dataType.includes('int') || 
                          column.dataType.includes('decimal') || 
                          column.dataType.includes('numeric') || 
                          column.dataType.includes('real') || 
                          column.dataType.includes('double')) {
                    data[key] = value ? Number(value) : null;
                } else {
                    data[key] = value;
                }
            }
        }
    }
    
    // 发送更新请求
    fetch(`/api/data/${tableInfo.name}/${tableInfo.recordId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.code === 200) {
            showSuccess('记录更新成功');
            setTimeout(() => {
                window.location.href = `/table/${tableInfo.name}`;
            }, 1000);
        } else {
            showError('更新失败: ' + result.message);
        }
    })
    .catch(error => {
        showError('网络错误: ' + error.message);
    });
});

// 显示错误
function showError(message) {
    document.getElementById('loadingState').style.display = 'none';
    document.getElementById('editCard').style.display = 'none';
    document.getElementById('errorState').style.display = 'block';
    document.getElementById('errorMessage').textContent = message;
}

// 显示成功消息
function showSuccess(message) {
    alert('成功: ' + message);
}

// 检查数组中是否包含某元素
function contains(array, element) {
    return array.indexOf(element) !== -1;
}
</script>
            </div>
        </div>
    </div>

    <footer class="bg-light py-4 mt-5">
        <div class="container text-center">
            <p class="text-muted mb-0">
                <i class="bi bi-heart-fill text-danger"></i>
                PGM - PostgreSQL管理平台 | 动态数据库管理工具
            </p>
        </div>
    </footer>

    <script src="/static/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="/static/js/app.js"></script>
</body>
</html>